package com.gd.coreservice.controller;


import com.gd.commonutils.Constants;
import com.gd.commonutils.Result;
import com.gd.coreservice.entity.Admin;
import com.gd.coreservice.entity.Users;
import com.gd.coreservice.entity.vo.UsersVo;
import com.gd.coreservice.service.UsersService;
import com.gd.coreservice.utils.TokenUtils;
import com.gd.servicebase.exceptionhandler.ServiceException;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author testjava
 * @since 2024-03-23
 */
@RestController
@RequestMapping("/users")
public class UsersController {
    @Autowired
    private UsersService usersService;
    //登录  已测试
    @GetMapping("/login")
    public Result login(@RequestParam String username,@RequestParam String password){
        if (usersService.login(username,password)!=null){
            String userId = usersService.findId(username);
            String token = TokenUtils.genToken(userId,password);
            UsersVo usersVo = usersService.login(username,password);
            usersVo.setToken(token);
            return Result.success(usersVo);
        }
        else {

            throw new ServiceException(Constants.CODE_600,"用户名或密码错误");
        }
    }
    //注册  已测试
    @PostMapping("/registerUser")
    public Result register(@RequestParam String username, @RequestParam String password){
        if(usersService.register(username,password))
        {
            return Result.success("注册成功");
        }
        else
        {
            throw new ServiceException(Constants.CODE_600, "该用户名已被注册");//自定义异常
        }
    }
    //修改个人密码  已测试
    @PutMapping("/updatePassword")
    public Result updatePassword(@RequestParam("Uid") String Uid,@RequestParam String password, @RequestParam String newpassword){
        //为了将前端传来的string类型转化为数据库对应的int类型，做出如下操作
        if(usersService.updatePassword(Uid,password, newpassword))
        {
            return Result.success("修改密码成功");
        }
        else
        {
            throw new ServiceException(Constants.CODE_600, "修改失败：密码错误");//自定义异常
        }
    }
    //查询所有的用户信息  已测试
    @GetMapping("/getUsers")
    public List<Users> getUsers() {
        return usersService.findAll();
    }

    //根据id查询数据  已测试 注意这里如果失败 返回结果不是json格式
    @GetMapping("/getOneUser")
    public Users findOne(@RequestParam("Uid") String Uid)
    {
        return usersService.findOne(Uid);
    }
    //表单新增
    //已测试 这里新增有问题  如果是把去掉一些关键字段的其余字段全部填入 则会新增失败（应该是和数据库字段设计有关）
    @PostMapping("/insertUser")
    public Result addStudent(@RequestBody Users users) {
        if(usersService.insertUsers(users))
        {
            return Result.success("添加成功");
        }
        else
        {
            throw new ServiceException(Constants.CODE_600, "用户名重复");//自定义异常
        }
    }
    //表单修改（根据uid去修改的） 已测试
    @PutMapping("/updateUser")
    public Result updateUser(@RequestBody Users users){
        if(usersService.updateUser(users))
        {
            return Result.success("修改成功");
        }
        else
        {
            throw new ServiceException(Constants.CODE_600, "修改出错");//自定义异常
        }
    }
    //删除 已测试
    @DeleteMapping("/deleteUser/{Uid}")
    public Integer deleteUser(@PathVariable("Uid") String Uid){
        return usersService.deleteUserById(Uid);
    }
    //批量删除 已测试
    @PostMapping("/deleteUser/batch")
    public Integer deleteUserBatch(@RequestBody List<String> Uids){
        return usersService.deleteUserBatch(Uids);
    }
    //分页查询 已测试
    @GetMapping("/getUserPage")
    public Map<String, Object> getUserPage(@RequestParam Integer pageNum,
                                              @RequestParam Integer pageSize,
                                              @RequestParam String username) {
        HashMap<String, Object> resultMap = new HashMap<>();
        Map<String, Object> result = usersService.getUserPageData(pageNum,pageSize,username);
        List<Users> data = (List<Users>) result.get("data");
        Long total = (Long) result.get("total");
        resultMap.put("data",data);
        resultMap.put("total",total);
        return resultMap;//返回结果Map集合：{data：List<User>集合，total：总的结果数} map集合.put添加key value
    }

    //查询用户总数 已测试
    @GetMapping("/getUserAllTotal")
    public int getAllTotal(){
        return usersService.getAllTotal();
    }
}

